package com.cn.client.controller;


import com.cn.api.*;
import com.cn.client.controller.api.OrderApi;
import com.cn.client.util.Tool;
import com.cn.client.vo.orderAndVisitorVo.*;
import com.cn.common.result.Result;
import com.cn.dot.AliPayDTO;
import com.cn.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


@Api(tags = "C端订单查询")
@RestController
@RequestMapping("/front/order")
public class OrderController implements OrderApi {
    @Resource
    private OrderCoreService orderCoreService;
    @Autowired
    private VisitorCoreService visitorCoreService;
    @Autowired
    private ProductCoreService productCoreService;

    @Autowired
    private StockService stockService;
    @Autowired
    private PriceService priceService;
    @Autowired
    private CouponFeignClient couponFeignClient;

    @ApiOperation(value = "查询出行人信息")
    @GetMapping("/findProductAndVisitor")
    @Override
    public Result findProductAndVisitor(Integer userId) {
        List<VisitorDTO> visitorDTO = visitorCoreService.findByVisitorId(userId);
        List<TravelerInformation> list = new ArrayList<>();
        for (VisitorDTO dto : visitorDTO) {
            TravelerInformation travelerInformation = new TravelerInformation();
            travelerInformation.setIdNumber(dto.getIdNumber());
            travelerInformation.setCertName(dto.getCertName());
            travelerInformation.setCert(dto.getCert());
            list.add(travelerInformation);
        }
        return Result.success(list);
    }


    @ApiOperation(value = "查询所有订单", notes = "有status是查询不同状态的订单")
    @GetMapping("/findAll")
    @Override
    public Result findAll(FindVo findVo) {
        ProductDTO productDTO = new ProductDTO();
        productDTO.setScenicId(findVo.getProductId());
        int productId = findVo.getProductId();
        FindDto findDto = new FindDto();
        findDto.setUserId(findVo.getUserId());
        findDto.setOrderStatus(findVo.getOrderStatus());
        findDto.setProductId(findVo.getProductId());
        List<OrderDTO> orderDTO = orderCoreService.findAll(findDto);
        List<OrderStatus> list = new ArrayList<>();
        for (OrderDTO dto : orderDTO) {
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setAmount(dto.getAmount());
            orderStatus.setOrderStatus(dto.getOrderStatus());
            orderStatus.setTicketName(productCoreService.findById(productId).getName());
            orderStatus.setTravelTime(dto.getTravelDate());
            list.add(orderStatus);
        }
        return Result.success(list);
    }

    @ApiOperation(value = "根据订单号查询订单详情")
    @GetMapping(value = "/findByOrderNumber")
    @Override
    public Result findByOrderNumber(String orderNumber) {
        OrderDTO orderDTO = orderCoreService.findByOrderNumber(orderNumber);
        List<VisitorDTO> visitorDTO = visitorCoreService.findByOrderNumber(orderNumber);
        OrderInformation orderInformation = new OrderInformation();
        orderInformation.setAmount(orderDTO.getAmount());
        orderInformation.setCouponAmount(orderDTO.getAmount());
        orderInformation.setOrderNumber(orderDTO.getOrderNumber());
        orderInformation.setTravelTime(orderDTO.getTravelDate());
        orderInformation.setScenicName(orderDTO.getOrderNumber());
        List<VisitorVo> visitorVoList = new ArrayList<>();
        for (int i = 0; i < visitorDTO.size(); i++) {
            VisitorVo visitorVo = new VisitorVo();
            visitorVo.setCertName(visitorDTO.get(i).getCertName());
            visitorVo.setIdNumber(visitorDTO.get(i).getIdNumber());
            visitorVoList.add(visitorVo);
        }
        orderInformation.setVisitorVoInformation(visitorVoList);
        return Result.success(orderInformation);
    }

    @ApiOperation(value = "生成订单")
    @PostMapping("/generateOrder")
    public Result generateOrder(@RequestBody GenerateOrder generateOrder) {
        //查询库存
        StockDTO stockDTO = stockService.findByProductId(generateOrder.getProductId());
        int number = generateOrder.getChildrenQuantity() + generateOrder.getAdultQuantity();
        if (stockDTO.getAvailableStock() <= number) {
            return Result.failed("库存不足");
        }
        int productId = generateOrder.getProductId();
        PriceDTO priceDTO1 = priceService.findByProductId(productId);
//        计算金额注入实体
        OrderDTO orderDTO = new OrderDTO();
        CountAmount countAmount= new CountAmount();
        countAmount.setAdultQuantity(generateOrder.getAdultQuantity());
        countAmount.setChildrenQuantity(generateOrder.getChildrenQuantity());
        countAmount.setCouponAmount(BigDecimal.valueOf(priceDTO1.getRetailPrice()));
        BigDecimal amount=Tool.CountAmount(countAmount);
        CouponDTO couponDTO=couponFeignClient.findById(generateOrder.getCouponId());
        //是否使用优惠券
        if (generateOrder.getCouponId()==null){
            orderDTO.setAmount(amount);
        }
        else {
            orderDTO.setAmount(Tool.CouponAmount(amount,couponDTO));
        }
        //生成订单号
        String orderNumber=Tool.CreateOrder(generateOrder);
        //生成订单
        orderDTO.setOrderNumber(orderNumber);
        orderDTO.setCouponId(generateOrder.getCouponId());
        orderDTO.setProductId(generateOrder.getProductId());
        orderDTO.setUserId(generateOrder.getUserId());
        orderDTO.setVisitorNumber(number);
        orderDTO.setTravelDate(generateOrder.getTravelTime());
        int order=orderCoreService.generateOrder(orderDTO);
        //添加订单和出行人关系
        List<Integer> visitorId =generateOrder.getVisitorId();
        orderCoreService.addRelation(orderNumber,visitorId);
        //扣减库存
        stockDTO.setPriceId(generateOrder.getProductId());
        stockDTO.setAvailableStock(number);
        int delete = stockService.update(stockDTO);
        //设置订单超时时间
        Jedis jedis=new Jedis();
        System.out.println(orderNumber);
        jedis.set(orderNumber,orderNumber);
        jedis.expire(orderNumber,1800);
        if (order==delete){
            return Result.success(order,"订单生成成功");
        }
        return Result.failed("订单生成失败");
    }

    @ApiOperation(value = "待付款取消订单")
    @GetMapping(value = "/cancelOrder")
    public Result cancelOrder(String orderNumber) {
        Jedis jedis=new Jedis();
        jedis.expire(orderNumber,1);
        if (true) {
            return Result.success(null, "订单已取消成功");
        }
        return Result.failed("订单取消失败");
    }

    @ApiOperation(value = "用户删除订单")
    @GetMapping(value = "/deleteOrder")
    public Result deleteOrder(String orderNumber) {
        int integer = orderCoreService.delete(orderNumber);
        if (integer == 1) {
            return Result.success(null, "订单删除成功");
        }
        return Result.failed("订单删除失败");
    }

    @ApiOperation(value = "根据订单号金额生成二维码")
    @PostMapping("/generateCode")
    public Result generateCode(String orderNumber,String totalAmount) {
        AliPayDTO aliPayDTO = new AliPayDTO();
        aliPayDTO.setTraceNo(orderNumber);
        aliPayDTO.setTotalAmount(totalAmount);
        String drCode = orderCoreService.generateCode(aliPayDTO);
        if (drCode!=null) {
            return Result.success(drCode,"二维码");
        }
        return Result.failed("二维码生成失败！");
    }
}
